package com.smartx.app.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.smartx.app.R;
import com.smartx.app.SatApp;
import com.smartx.app.util.QRCodeUtil;

public class ReceiveFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = "wallet";
    private ImageView qrImageView = null;
    private TextView  suggestionAddressView = null;
    private TextView  addressTextView = null;
    private Button copyAddressButton = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_receive,container,false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        qrImageView = (ImageView)view.findViewById(R.id.qr_image);
        suggestionAddressView = (TextView)view.findViewById(R.id.address_suggestion);
        addressTextView = (TextView)view.findViewById(R.id.address);
        copyAddressButton = (Button)view.findViewById(R.id.copy_action);
        copyAddressButton.setOnClickListener(this);

        refreshAddressQrCode();
    }

    private void refreshAddressQrCode(){
        String coinbase = SatApp.getInstance().getCoinBaseAddress();
        if(coinbase == null || coinbase.isEmpty()){
            return;
        }
        Bitmap bitmap = QRCodeUtil.createQRCode(SatApp.getInstance().getCoinBaseAddress());
        qrImageView.setImageBitmap(bitmap);
    }

    private void copyAddressToClipBoard(){
        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("",SatApp.getInstance().getCoinBaseAddress());
        cm.setPrimaryClip(mClipData);
    }

    @Override
    public void onResume(){
        super.onResume();
        refreshAddressQrCode();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.copy_action:
                Log.d(TAG,"copy address " + SatApp.getInstance().getCoinBaseAddress() + " to clip board");
                copyAddressToClipBoard();
                break;
        }
    }
}
